package com.yuan.leetcode.JianZhiOffer;

/**
 * Created by yuanhaowu
 * Time 2022/6/9 15:15
 */
public class offer12 {

    public boolean exist(char[][] board, String word) {
        if (board == null || board.length == 0 || board[0].length == 0) {
            return false;
        }
        char[] wordArray = word.toCharArray();
        boolean[][] dp = new boolean[board.length][board[0].length];
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (dfs(board, wordArray, dp, i, j, 0)) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean dfs(char[][] board, char[] wordArray, boolean[][] dp, int i, int j, int start) {
        if (i < 0
                || i >= board.length
                || j < 0
                || j >= board[0].length
                || wordArray[start] != board[i][j]
                || dp[i][j]) {
            return false;
        }
        if (start == wordArray.length - 1) {
            return true;
        }
        dp[i][j] = true;
        boolean res = dfs(board, wordArray, dp, i + 1, j, start + 1)
                || dfs(board, wordArray, dp, i, j + 1, start + 1)
                || dfs(board, wordArray, dp, i - 1, j, start + 1)
                || dfs(board, wordArray, dp, i, j - 1, start + 1);
        dp[i][j] = false;
        return res;
    }
}
